<?php

namespace Common\Lib\Payments\WapWechat;

use Common\Lib\Payments\PaymentPlugin;

/**
 * @class alipay
 * @brief 微信支付
 */
class WapWechat extends PaymentPlugin {

    public $name = '手机端微信支付';
    protected $Api;

    public function __construct($payment, $backParam = array()) {
        parent::__construct($payment, $backParam);
        $this->serverCallbackUrl = U('/payment/callback', array_merge($backParam,array('_id' => $this->paymentId, '_notify' => 1)),false,true).'/';
        include_once("WxPayPubHelper/WxPayPubHelper.php");
        include_once("WxPayPubHelper/SDKRuntimeException.php");
        include_once("WxPayPubHelper/WxPay.pub.config.php");
        $this->initConfig($payment);
        $this->Api = new \JsApi_pub();
    }

    public function initConfig($payment) {
        \WxPayConf_pub::$APPID = $this->config('appid');
        \WxPayConf_pub::$MCHID = $this->config('mch_id');
        \WxPayConf_pub::$KEY = $this->config('key');
        \WxPayConf_pub::$APPSECRET = $this->config('appsecret');        
        \WxPayConf_pub::$SSLCERT_PATH = dirname(__FILE__) . '/WxPayPubHelper/cert/apiclient_cert.pem';
        \WxPayConf_pub::$SSLKEY_PATH = dirname(__FILE__) . '/WxPayPubHelper/cert/apiclient_key.pem';
        \WxPayConf_pub::$NOTIFY_URL = $this->serverCallbackUrl;
    }

    public function notifyStop() {
        echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        exit;
    }

    public function getSubmitUrl() {
        
    }

    public function getSendData($payment) {
		\WxPayConf_pub::$JS_API_CALL_URL = U('payment/dopay',['method'=>$this->paymentId,'order_id'=>$payment['M_OrderNO']],true,true);
        $openid = $this->getOpenId();
        $unifiedOrder = new \UnifiedOrder_pub();
        $unifiedOrder->setParameter("openid", $openid); //商品描述
        $unifiedOrder->setParameter("body", "会员"); //商品描述
        $unifiedOrder->setParameter("out_trade_no", $payment['M_OrderNO']); //商户订单号 
        $unifiedOrder->setParameter("total_fee", $payment['M_Amount'] * 100); //总金额
        $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::$NOTIFY_URL); //通知地址 
        $unifiedOrder->setParameter("trade_type", "JSAPI"); //交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号 
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据 
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID

        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $this->Api->setPrepayId($prepay_id);
        $jsApiParameters = $this->Api->getParameters();

        $html = <<<str
    <html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <title>微信安全支付</title>

	<script type="text/javascript">

		//调用微信JS api 支付
		function jsApiCall()
		{
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest',
				{$jsApiParameters},
				function(res){				
					WeixinJSBridge.log(res.err_msg);
                                        if(res.err_msg == 'get_brand_wcpay_request:ok'){ 
                                            alert('恭喜您,支付成功!');
                                            location.href='http://lmshop.06050.cn/Member/index';                                            
                                        }else if(res.err_msg == 'get_brand_wcpay_request:cancel'){ 
                                            location.href='http://lmshop.06050.cn/Member/index';        
                                        }else if(res.err_msg == 'get_brand_wcpay_request:fail'){ 
                                              alert('支付失败');
                                             location.href='http://lmshop.06050.cn/Member/index'
                                        }
				}
			);
		}

		function callpay()
		{                   
			if (typeof WeixinJSBridge == "undefined"){                            
			    if( document.addEventListener ){
			        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			    }else if (document.attachEvent){
			        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
			        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			    }
			}else{
			    jsApiCall();
			}
		}
	</script>
</head>
<body>
	<script>
                callpay();
          
       </script>
</body>
</html>
str;
        echo $html;
        exit;
    }

    public function getOpenId() {
        if ($_GET['code']) {
            $code = $_GET['code'];
            $this->Api->setCode($code);
            return $this->Api->getOpenId();
        } else {
            $url = $this->Api->createOauthUrlForCode(\WxPayConf_pub::$JS_API_CALL_URL);
            Header("Location: $url");
            return;
        }
    }

    public function serverCallbackUrl($callbackData) {
        $this->isNotify = true;
        $xml = $GLOBALS['HTTP_RAW_POST_DATA']; 
        $reply = $this->reply();
        $notify = new \Notify_pub();
        $notify->saveData($xml);
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
            $reply->orderNo = $notify->data['out_trade_no'];
            $reply->money = $notify->data['total_fee'] / 100;
            $reply->setStatus(true);
        }
        return $reply;
    }

    public function callback($callbackData) {
        return $this->serverCallbackUrl($callbackData);
    }

    public function notifyCallback($callbackData) {
        return $this->serverCallbackUrl($callbackData);
    }

    /**
     * @brief 返回配置参数
     */
    public function configParam() {
        return array(
            'appid' => '公众账号ID',
            'mch_id' => '商户号',
            'key' => 'API密钥',
            'appsecret'=>'App Secret'
        );
    }

}
